package com.innotek.testworkstation.common.restassured;
import com.alibaba.fastjson.JSONObject;
import com.innotek.testworkstation.config.Constant;
import com.innotek.testworkstation.util.CachePool;
import com.innotek.testworkstation.util.FastJsonUtils;
import io.restassured.RestAssured;
import io.restassured.builder.ResponseBuilder;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import lombok.extern.slf4j.Slf4j;
import com.innotek.testworkstation.common.restassured.apipage.PageModel;
import com.innotek.testworkstation.util.PropertyUtil;

import java.io.IOException;
import java.util.HashMap;
import static org.hamcrest.Matchers.equalTo;



/**
 * @ClassName ApiBefore
 * @Description 测试前置操作
 * @Author wangx
 * @Date 2021/7/8 下午5:32
 * @Version 1.0
 **/
@Slf4j
public class ApiBefore {
    private static ApiBefore apiBefore;
    private static PageModel pageApi;

    public static ApiBefore getInstance(){
        if(apiBefore==null){
            apiBefore=new ApiBefore();
        }
        return apiBefore;
    }

    public String getWebToken() {
        String tokenWeb= CachePool.getInstance().getStringCacheItem("web.token");
        if(tokenWeb==null || tokenWeb.equals("")){
            try {
                pageApi = PageModel.loadApi("src/main/resources/restassured/pageapi/web/base.yaml");
                Response response = new RunRequest().run(Constant.PROJECT_WEB,pageApi.actions.get("login"));
                response.then().statusCode(200).body("msg", equalTo(Constant.RES_MSG_TRUE));
                tokenWeb = response.body().path("data.token");
                log.info("web登录成功");
            } catch (IOException e) {
                log.error("尝试web登录失败:{}", e.getMessage());
            }

            // 写入临时配置文件
            CachePool.getInstance().putCacheItem("web.token", tokenWeb);
        }else{
            tokenWeb = CachePool.getInstance().getStringCacheItem("web.token");
        }

        return tokenWeb;
    }

    public String getPosToken() {
        String tokenPos= CachePool.getInstance().getStringCacheItem("pos.token");
        if(tokenPos==null || tokenPos.equals("")){
            String terminalId="";
            try {
                pageApi = PageModel.loadApi("src/main/resources/restassured/pageapi/pos/pos.yaml");
                Response response = new RunRequest().run(Constant.PROJECT_POS,pageApi.actions.get("login"));
                response.then().statusCode(200).body("msg", equalTo(Constant.RES_MSG_TRUE));
                tokenPos = response.body().path("data.token");
                // 获取terminalId
                terminalId = response.body().path("data.terminalId");
                log.info("POS登录成功");
            } catch (IOException e) {
                log.error("尝试POS登录失败:{}", e.getMessage());
            }

            HashMap<String, Object> d = new HashMap<>();
            d.put("pos.token", tokenPos);
            d.put("terminalId",terminalId);
            // 写入临时配置文件
            CachePool.getInstance().putCacheAllItem(d);
        }else{
            tokenPos = CachePool.getInstance().getStringCacheItem("pos.token");
        }

        return tokenPos;
    }



    public void runBefore() { // 前置操作
        // 把web的token加入参数
        String tokenWeb = getWebToken();
        // 把pos的token加入参数
        String tokenPos = getPosToken();

        RestAssured.filters((req, res, ctx) -> {
            req.contentType(ContentType.JSON); // 转成JSON
            JSONObject fastJson = FastJsonUtils.getJson(req.getBody());
            String source = String.valueOf(fastJson.get("source"));
            // 判断请求里的来源，插入相应的token
            if(source.equals(Constant.SOURCE_WEB)){
                req.header("POAuthorization",tokenWeb);
            }else if(source.equals(Constant.SOURCE_POS)){
                req.header("PTIAuthorization",tokenPos);
            }
            Response resOrigin=ctx.next(req, res);
            ResponseBuilder responseBuilder=new ResponseBuilder().clone(resOrigin);
            return responseBuilder.build();
        });
    }


}
